import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { useEffect, useState } from 'react';
import {
  replaceImagesFileSourceWithInlineRepresentation,
  findAllImgSrcsFromHtml,
  extractImageDataFromRtf,
} from './utils';
// import module from '../uploadDownload/index';
// Boot.registerModule(module);
function MyEditor(props) {
  // editor 实例
  const [editor, setEditor] = useState(null); // JS 语法
  // 编辑器内容
  const [html, setHtml] = useState(props.myEditorHtml);

  //imgList
  const [imgList, setImgList] = useState([]);
  // 模拟 ajax 请求，异步设置 html
  useEffect(() => {
    setHtml(props.myEditorHtml);
  }, [props.myEditorHtml]);

  // 工具栏配置
  const toolbarConfig = {}; // TS 语法
  toolbarConfig.toolbarKeys = [
    'bold',
    'underline',
    'italic',
    {
      key: 'group-more-style',
      title: '更多',
      iconSvg:
        '<svg viewBox="0 0 1024 1024"><path d="M204.8 505.6m-76.8 0a76.8 76.8 0 1 0 153.6 0 76.8 76.8 0 1 0-153.6 0Z"></path><path d="M505.6 505.6m-76.8 0a76.8 76.8 0 1 0 153.6 0 76.8 76.8 0 1 0-153.6 0Z"></path><path d="M806.4 505.6m-76.8 0a76.8 76.8 0 1 0 153.6 0 76.8 76.8 0 1 0-153.6 0Z"></path></svg>',
      menuKeys: ['through', 'code', 'sup', 'sub', 'clearStyle'],
    },
    'color',
    'bgColor',
    '|',
    'fontSize',
    'fontFamily',
    'lineHeight',
    '|',
    'todo',
    {
      key: 'group-justify',
      title: '对齐',
      iconSvg:
        '<svg viewBox="0 0 1024 1024"><path d="M768 793.6v102.4H51.2v-102.4h716.8z m204.8-230.4v102.4H51.2v-102.4h921.6z m-204.8-230.4v102.4H51.2v-102.4h716.8zM972.8 102.4v102.4H51.2V102.4h921.6z"></path></svg>',
      menuKeys: ['justifyLeft', 'justifyRight', 'justifyCenter', 'justifyJustify'],
    },
    {
      key: 'group-indent',
      title: '缩进',
      iconSvg:
        '<svg viewBox="0 0 1024 1024"><path d="M0 64h1024v128H0z m384 192h640v128H384z m0 192h640v128H384z m0 192h640v128H384zM0 832h1024v128H0z m0-128V320l256 192z"></path></svg>',
      menuKeys: ['indent', 'delIndent'],
    },
    '|',
    'emotion',

    'redo',
    'fullScreen',
  ];

  const txtToolbarConfig = {}
  txtToolbarConfig.toolbarKeys = [
    // 'headerSelect',
    'blockquote',
    '|',
    'bold',
    'underline',
    'italic',
    {
      key: 'group-more-style',
      title: '更多',
      iconSvg:
        '<svg viewBox="0 0 1024 1024"><path d="M204.8 505.6m-76.8 0a76.8 76.8 0 1 0 153.6 0 76.8 76.8 0 1 0-153.6 0Z"></path><path d="M505.6 505.6m-76.8 0a76.8 76.8 0 1 0 153.6 0 76.8 76.8 0 1 0-153.6 0Z"></path><path d="M806.4 505.6m-76.8 0a76.8 76.8 0 1 0 153.6 0 76.8 76.8 0 1 0-153.6 0Z"></path></svg>',
      menuKeys: ['through', 'code', 'sup', 'sub', 'clearStyle'],
    },
    'color',
    'bgColor',
    '|',
/*    'fontSize',
    'fontFamily',*/
    'lineHeight',
    '|',
    'emotion',
    'undo',
    'redo',
    'fullScreen',
  ]
  // 编辑器配置
  const editorConfig = {
    // 在编辑器中，点击选中“附件”节点时，要弹出的菜单
    MENU_CONF: {
      //上传照片
      uploadImage: {
        // 单个文件的最大体积限制，默认为 2M
        maxFileSize: 50 * 1024 * 1024, // 50M
        // 超时时间，默认为 10 min
        timeout: 10 * 60 * 1000,
        fieldName: 'file',
        server: '/api/v1/topic/batchUpload', // 服务端地址
        // 上传成功后，用户自定义插入文件
        // 自定义插入图片
        customInsert(res, insertFn) {
          // TS 语法
          // customInsert(res, insertFn) {                  // JS 语法
          // res 即服务端的返回结果
          // 从 res 中找到 url alt href ，然后插入图片
          const element = res.data[0];
          props.setEditorFileList([
            ...props.editorFileList,
            {
              id: element.fileId,
              kind: 'richtext',
              localurl: element.url,
              origin: 'topic',
              pxh: 10,
              wjdx: element.fileSize,
              wjgs: element.fileType,
              wjmc: element.fileName,
            },
          ]);
          insertFn('' + res.data[0].path, res.data[0].fileId);
        },
        // 插入到编辑器后的回调
        onInsertedAttachment(elem) {
          console.log('inserted attachment', elem);
        },
      },
      fontFamily:{
        fontFamilyList:[
          '宋体',
          '方正小标宋',
          '方正仿宋',
          '方正楷体',
          '方正黑体',
          '仿宋',
          '隶书',
          '微软雅黑',
          '楷体',
          '黑体',
          '幼圆',
          '华文行楷',
          '华文隶书',

        ]
      },
      fontSize:{
        fontSizeList: [
            {
              "name": "初号",
              "value": "56px"
            }, {
              "name": "小初",
              "value": "48px"
            },
          {
            "name": "一号",
            "value": "34.7px"
          },{
            "name": "小一",
            "value": "32px"
          },
          {
            "name": "二号",
            "value": "29.3px"
          },
          {
            "name": "小二",
            "value": "24px"
          },
          {
            "name": "三号",
            "value": "21.3px"
          },{
            "name": "小三",
            "value": "20px"
          },{
            "name": "四号",
            "value": "18.7"
          },
          {
            "name": "小四",
            "value": "16px"
          },
          {
            "name": "五号",
            "value": "14px"
          },
          {
            "name": "小五",
            "value": "12px"
          },
          {
            "name": "六号",
            "value": "10px"
          },
          {
            "name": "小六",
            "value": "8.7px"
          },
          {
            "name": "七号",
            "value": "7.3px"
          },
          {
            "name": "八号",
            "value": "6.7px"
          },
            "12px",
            {
              "name": "13px",
              "value": "13px"
            },
            "14px",
            "15px",
            "16px",
            "19px",
            {
              "name": "22px",
              "value": "22px"
            },
            "24px",
            "29px",
            "32px",
            "40px",
            "48px"
          ]

      }
    },
    placeholder: '请输入内容...',
  };

  // 自定义粘贴
  editorConfig.customPaste = (editor, event) => {
    // 获取粘贴的html部分（？？没错粘贴word时候，一部分内容就是html），该部分包含了图片img标签
    let html = event.clipboardData.getData('text/html');

    // 获取rtf数据（从word、wps复制粘贴时有），复制粘贴过程中图片的数据就保存在rtf中
    const rtf = event.clipboardData.getData('text/rtf');
    if (html && rtf) {
      // 该条件分支即表示要自定义word粘贴

      // 列表缩进会超出边框，直接过滤掉

      html = html.replace(/text\-indent:\-(.*?)pt/gi, '');
      html = html.replace(/<xml>[/s/S]*?<\/xml>/gi, '');
      // html= html.replace(/<style>[/s/S]*?<\/style>/gi, '');
      // html= html.replace(/<h1>[/s/S]*?<\/h1>/gi, '');
      // let arr = html.match(/<strong>[\s\S]*?<\/strong>/gi); //筛选出所有的img
      // let arr2 = html.match(/<strong><span[\s\S]*?<\/strong>/gi); //筛选出所有的img
      // for (let i = 0; i < arr.length; i++) {
      //   const element = arr[i];
      //   let arr1 = element.match(/<span>[\s\S]*?<\/span>/gi); //筛选出所有的img

      // }
      // 从html内容中查找粘贴内容中是否有图片元素，并返回img标签的属性src值的集合
      const imgSrcs = findAllImgSrcsFromHtml(html);

      // 如果有
      if (imgSrcs && Array.isArray(imgSrcs) && imgSrcs.length) {
        // 阻止默认的粘贴行为
        event.preventDefault();
        // 从rtf内容中查找图片数据
        const rtfImageData = extractImageDataFromRtf(rtf);

        // 如果找到
        if (rtfImageData.length) {
          // TODO：此处可以将图片上传到自己的服务器上

          // 执行替换：将html内容中的img标签的src替换成ref中的图片数据，如果上面上传了则为图片路径
          html = replaceImagesFileSourceWithInlineRepresentation(html, imgSrcs, rtfImageData, true);
          editor.dangerouslyInsertHtml(html);
        }
      } else {
        console.log(html);
        editor.dangerouslyInsertHtml(html);
      }
      return false;
    } else {
      return true;
    }
  };

  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  return (
    <>
      <div style={{ border: '1px solid #ccc', zIndex: 100 ,width:'1000px'}}>
        <Toolbar
          editor={editor}
          defaultConfig={props.type == 'text' ? txtToolbarConfig : toolbarConfig}
          mode="default"
          style={{ borderBottom: '1px solid #ccc' ,width:'100%'}}
        />

        <Editor
          defaultConfig={editorConfig}
          value={html}
          onCreated={setEditor}
          onChange={(editor) => {
            props.setMyEditorHtml(editor.getHtml());
            setHtml(editor.getHtml());
          }}
          mode="default"
          style={{ height: props.type == 'text' ? '100px' :'500px',  overflowY: 'hidden' ,width:'100%' }}
        />
      </div>
    </>
  );
}

export default MyEditor;
